package cn.watson.basic.utils;

import cn.watson.basic.constant.BaseConstants;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
* @Description: 短信发送工具类。官网复制过来的
* @Author: ZhangRui
* @Version: 1.0
* @Date:  2022/7/6 12:42
*/
import java.io.IOException;

public class SmsUtil {

    public static void sendCode(String phone, String smsCodeValue){
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("https://utf8api.smschinese.cn/");
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
            // SMS_UID 和  SMS_KEY 在公共BaseConstants，中已经定义好了。这里调用即可 。下面为源代码样式
            // NameValuePair[] data ={ new NameValuePair("Uid", "Zhang_rui"),new NameValuePair("Key", "5074A11E5F01AE9ACCE180BACBD9F498"),new NameValuePair("smsMob","手机号码"),new NameValuePair("smsText","验证码：8888")};
            NameValuePair[] data ={ new NameValuePair("Uid", BaseConstants.SmsConstant.SMS_UID),
                    new NameValuePair("Key", BaseConstants.SmsConstant.SMS_KEY),
                    new NameValuePair("smsMob",phone), // 手机号 ：phone
                    new NameValuePair("smsText",smsCodeValue)}; // 验证码：smsCodeValue
            post.setRequestBody(data);

            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode); //HTTP状态码
            for(Header h : headers){
                System.out.println(h.toString());
            }
            String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
            System.out.println(result);  //打印返回消息状态
            post.releaseConnection();
        } catch (
        IOException e) {
            e.printStackTrace();
        }
    }

    // 测试
    public static void main(String[] args) {
        sendCode("17745094783", "亲，您的验证码是："+9527+"，请在三分钟内使用！");
    }

}
